<template>
  <div class="app-container">

    <div class="filter-container">
      <el-select @change="getRecords"  v-model="query.selectType" style="width: 200px;margin-right: 5px;" class="filter-item">
        <el-option v-for="(item,index) in mapType" :key="index" :label="item.label " :value="item.value" />
      </el-select>
      <el-button @click="openAddDialog" type="primary" class="filter-item">添加</el-button>
      <el-button @click="reload" type="danger" class="filter-item">刷新</el-button>
    </div>

      <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
    <el-table-column
      type="selection"
      width="55" />
    <el-table-column prop="id" label="ID" width="80" />
    <el-table-column prop="type" label="类型" width="120" />
    <el-table-column prop="title" label="标题" width="150" />
    <el-table-column prop="pic_url" label="图片" width="150" >
      <template slot-scope="scope">
        <img v-if="scope.row.pic_url" class="table-img" :src="host+scope.row.pic_url">
      </template>
    </el-table-column>
    <el-table-column prop="link" label="点击链接" width="150" />
    <el-table-column prop="status" label="状态" width="150" >

      <template slot-scope="scope">
        <el-switch
          v-model="scope.row.status"
          active-color="#409EFF"
          inactive-color="#909399"
          :active-value="1"
          :inactive-value="2"
          @change="changeSwitch(scope.row)">
        </el-switch>
      </template>

    </el-table-column>
    <el-table-column prop="created_at" label="创建时间" width="160" />
    <el-table-column fixed="right" label="操作" width="200">
      <template slot-scope="scope">
		<el-button
			size="mini"
			@click="handleEdit(scope.$index, scope.row)">编辑</el-button>
			<el-button
			size="mini"
			type="danger"
			@click="handleDelete(scope.$index, scope.row)">删除</el-button>
		</template>
    </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.page"
      :page-sizes="[10, 20, 100, 200]"
      :page-size="pagination.pageSize"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total">
    </el-pagination>

    <el-dialog title="添加广告" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" label-width="80px">

        <el-form-item label="上传">
          <el-upload
            class="avatar-uploader"
            action="/guard/upload"
            accept=".png,.jpg,.jpeg"
            :show-file-list="false"
            :data="upload"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload">
            <img v-if="urlImage" :src="urlImage" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="频道">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option
              v-for="item in mapType"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="图片地址">
          <el-input v-model="form.pic_url"></el-input>
        </el-form-item>
        <el-form-item label="点击链接">
          <el-input v-model="form.link"></el-input>
        </el-form-item>

        <el-form-item label="状态">
          <el-switch
            v-model="form.status"
            active-color="#409EFF"
            inactive-color="#909399"
            :active-value="1"
            :inactive-value="2"
            >
          </el-switch>
        </el-form-item>
        <el-form-item v-if="isAdd">
          <el-button type="primary" @click="onSubmit('form')">立即创建</el-button>
        </el-form-item>
        <el-form-item v-else>
          <el-button type="primary" @click="onSubmit('form')">修改</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>



</template>

<script>

import { myGet, myPost } from '@/utils/myRequest'

const urlAdvertLst = '/guard/advert/lst'
const urlAdvertAdd = '/guard/advert/add'
const urlAdvertDel = '/guard/advert/del'
const urlAdvertGet = '/guard/advert/getAdvert'

export default {

    data() {
      return {
        host:process.env.VUE_APP_HOST,
        list:[],
        isAdd:true,
        dialogFormVisible:false,
        listLoading:false,
        urlImage:'',
        mapType:[],
        query:{
          selectType:'',
          name:''
        },
        pagination:{
          page:1,
          pageSize:10,
          total:0,
        },
        form:{
          type:0,
          title:'',
          pic_url:'',
          link:'',
          status:1,
        },

        upload:{
          module:'advert',
        }
      }
    },
    methods: {
      reload(){
        Object.assign(this.$data.query,this.$options.data().query)
        Object.assign(this.$data.pagination,this.$options.data().pagination)
        this.getRecords()
      },
      getRecords(){
        this.listLoading = true
        myGet(urlAdvertLst,{type:this.query.selectType}).then(res=>{
          this.listLoading = false
          if(res.status){
            this.list = res.data.records
            res.data.map_type.forEach(item=>{
              this.mapType.push({
                value:item.value,
                label:item.label
              })
            })
          }
        })
      },
      changeSwitch(row){
        myPost(urlAdvertAdd,{ id:row.id, status:row.status }).then(res=>{
          if(res.status){
            this.$message.success(res.msg)
          }
        })
      },
      openAddDialog(){
        this.dialogFormVisible= true
        Object.assign(this.form,this.$options.data().form)
      },
      closeAddDialog(){
        Object.assign(this.form,this.$options.data().form)
        this.dialogFormVisible= false
      },

      onSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
              this.dialogFormVisible = true;
              myPost(urlAdvertAdd,this.form).then(res=>{
                this.dialogFormVisible = false;
                if(res.status){
                  this.$message.success(res.msg);
                  this.getRecords()
                }
              })
          } else {
              this.$message.error('验证失败！');
              return false;
          }
        });
        },
      handleUploadSuccess(res, file) {
        if(res.status){
            this.urlImage = res.data.records.url
            this.form.pic_url = res.data.records.filePath
        }else{
            this.$message.error(res.msg)
        }
      },
      beforeUpload(file) {
          const isLt2M = file.size / 1024 / 1024 < 2;
          if (!isLt2M) {
              this.$message.error('上传头像图片大小不能超过 2MB!');
          }
          return isLt2M;
      },

      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSizeChange(val) {
        this.pagination.pageSize = val
        this.pagination.page = 1
        this.getRecords()
      },
      handleCurrentChange(val) {
        this.pagination.page  = val
        this.getRecords();
      },

      handleEdit(index,row){
        this.isAdd = false
        let id = row.id

        myGet(urlAdvertGet,{id}).then(res=>{
          if(res.status){
            let advert = res.data.records[0];
            advert.pic_url = this.host+advert.pic_url
            Object.assign(this.form,advert)
            this.dialogFormVisible = true
          }
        })
      },

      handleDelete(index,row){

        this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let id = row.id
          myGet(urlAdvertDel,{id}).then(res => {
            if(res.status){
              this.$message.success(res.msg)
              this.getRecords()
            }
          })
        })
      }
    },

    mounted() {
      this.getRecords()
    },
}
</script>

<style>

.table-img{
    width: 50px;
    height: 50px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
